google storage api | | test create bucket | Search

This code defines functions for managing Google Cloud Storage buckets, including listing existing buckets, creating new ones, and setting public access.

Run example

npm run import -- "create a bucket"

create a bucket

var qs = require('querystring');
var importer = require('../Core');
var authorizeGoogle = importer.import("authorize google service");

// TODO: set index page

function safeName(name) {
    return name.replace(/[^a-z0-9\-\.]/ig, '-').toLowerCase();
}

function setPublic(project, bucketName) {
    var client;
    // TODO:
    return authorizeGoogle()
        .then(c => client = c)
        .then(() => client.request({
            method: 'POST',
            url: `https://www.googleapis.com/storage/v1/b/${qs.escape(bucketName)}/acl`,
            data: {
                entity: 'allUsers',
                role: 'READER'
            }
        }))
        .then(() => client.request({
            method: 'POST',
            url: `https://www.googleapis.com/storage/v1/b/${qs.escape(bucketName)}/defaultObjectAcl`,
            data: {
                entity: 'allUsers',
                role: 'READER'
            }
        }))
}

function listBuckets(project, bucketName) {
    var params = {project: project};
    if(bucketName) {
        params.prefix = bucketName;
    }
    return authorizeGoogle()
        .then(client => client.request({
            url: `https://www.googleapis.com/storage/v1/b`,
            params
        }))
        .then(response => response.data.items || [])
}

function addBucket(project, bucketName) {
    return authorizeGoogle()
        .then(client => client.request({
            method: 'POST',
            url: `https://www.googleapis.com/storage/v1/b`,
            params: {project: project},
            data: {
                name: bucketName,
                location: 'us-central1',
                storageClass: 'regional',
                website: {
                    mainPageSuffix: 'index.html'
                }
            }
        }))
        .then(response => response.data.name)
        .then(() => setPublic(project, bucketName))
}

function createBucket(project, bucketName) {
    bucketName = safeName(bucketName);
    return listBuckets(project, bucketName)
        .then(buckets => {
            if(buckets.length > 0) {
                console.log(`bucket ${bucketName} already exists`);
                return Promise.resolve(buckets[0].name);
            }
            return addBucket(project, bucketName)
        })
        .then(() => bucketName);
}

module.exports = createBucket;

What the code could have been:

const querystring = require('querystring');
const { authorizeGoogleService } = require('../Core');
const { google } = require('googleapis');

/**
 * Creates a safe name by replacing non-alphanumeric characters with hyphens and converting to lowercase.
 *
 * @param {string} name - The name to make safe.
 * @returns {string} The safe name.
 */
function safeName(name) {
    return name.toLowerCase().replace(/[^a-z0-9\-\.]+/gi, '-');
}

/**
 * Sets public access to a bucket.
 *
 * @param {string} project - The project ID.
 * @param {string} bucketName - The name of the bucket.
 * @returns {Promise} A promise that resolves when the public access is set.
 */
function setPublic(project, bucketName) {
    const storage = google.storage('v1');
    return authorizeGoogleService()
       .then((auth) => storage.projects.messages.create({
            auth,
            resource: {
                mailbox: bucketName,
                received: {
                    sender: 'allUsers',
                    role: 'READER'
                }
            }
        }))
       .then((response) => {
            const defaultObjectAcl = response.data;
            return defaultObjectAcl? defaultObjectAcl.id : null;
        })
       .then((defaultObjectAclId) => {
            if (!defaultObjectAclId) {
                return authorizeGoogleService()
                   .then((auth) => storage.buckets.get({
                        auth,
                        resource: bucketName,
                    }));
            }
            const acl = {
                bucket: bucketName,
                entity: 'allUsers',
                role: 'READER',
                id: defaultObjectAclId
            };
            return storage.buckets.setAcl({
                auth,
                resource: acl,
            });
        });
}

/**
 * Lists buckets in a project.
 *
 * @param {string} project - The project ID.
 * @param {string} [bucketName] - The name of the bucket (optional).
 * @returns {Promise} A promise that resolves with the list of buckets.
 */
function listBuckets(project, bucketName) {
    const storage = google.storage('v1');
    const params = { project };
    if (bucketName) {
        params.prefix = bucketName;
    }
    return authorizeGoogleService()
       .then((auth) => storage.buckets.list({
            auth,
            params
        }))
       .then((response) => response.data.items || []);
}

/**
 * Adds a bucket to a project.
 *
 * @param {string} project - The project ID.
 * @param {string} bucketName - The name of the bucket.
 * @returns {Promise} A promise that resolves with the name of the bucket.
 */
function addBucket(project, bucketName) {
    const storage = google.storage('v1');
    return authorizeGoogleService()
       .then((auth) => storage.buckets.insert({
            auth,
            resource: {
                name: bucketName,
                location: 'us-central1',
                storageClass:'regional',
                website: {
                    mainPageSuffix: 'index.html'
                }
            }
        }))
       .then((response) => response.data.name)
       .then((bucketName) => setPublic(project, bucketName));
}

/**
 * Creates a bucket in a project.
 *
 * @param {string} project - The project ID.
 * @param {string} bucketName - The name of the bucket.
 * @returns {Promise} A promise that resolves with the name of the bucket.
 */
function createBucket(project, bucketName) {
    bucketName = safeName(bucketName);
    return listBuckets(project, bucketName)
       .then((buckets) => {
            if (buckets.length > 0) {
                console.log(`bucket ${bucketName} already exists`);
                return Promise.resolve(buckets[0].name);
            }
            return addBucket(project, bucketName)
               .then(() => bucketName);
        });
}

module.exports = createBucket;

This code snippet provides a set of functions for interacting with Google Cloud Storage buckets.

Here's a breakdown:

  1. Dependencies:

  2. Helper Functions:

  3. Bucket Management Functions:

Let me know if you have any more code snippets you'd like me to explain!